package com.ithema.controller;

import com.ithema.entity.Result;
import com.ithema.entity.User;
import com.ithema.service.UserService;
import com.ithema.utils.ThreadLocalUtil;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")

public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 注册
     *
     * @param user
     * @return
     */
    @PostMapping("/register")
    public Result register(@RequestBody @Validated User user) {
        int register = userService.register(user);
        if (register == 1) {
            //注册失败
            return Result.error("注册失败，用户名已存在");
        }
        return Result.success("注册成功");
    }

    @PostMapping("/login")
    public Result login(String username, String password) {
        Result login = userService.login(username, password);
        return login;
    }

    @PostMapping("/userInfo")
    public Result<User> userInfo() {
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUserName(username);
        return Result.success(user);
    }

    @PostMapping("/update")
    public Result<User> update(@RequestBody @Validated User user) {
        int update = userService.update(user);
        if (update == 0) {
            //注册失败
            return Result.error("修改失败");
        }
        return Result.success();
    }

    @PostMapping("/updateAvatar")
    public Result<User> updateAvatar(@RequestParam @URL String avatar) {
        int i = userService.updateAvatar(avatar);
        if (i == 0) {
            //修改失败
            return Result.error("修改失败");
        }
        return Result.success();
    }

    @PostMapping("/updatePassword")
    public Result<User> updatePassword(@RequestBody Map<String, String> password) {
        if (password.get("reNewPassword").equals(password.get("newPassword"))) {
            int i = userService.updatePassword(password.get("oldPassword"), password.get("newPassword"));
            if (i == 0) {
                return Result.error("原密码错误，修改失败");
            }
            return Result.success();
        } else {
            return Result.error("两次密码不一致");
        }
    }
}
